﻿using MapleLeaf.Application.CookBook;
using MapleLeaf.Application.CookBook.Models;
using MapleLeaf.Core;
using MapleLeaf.Core.Cache.Redis;
using MapleLeaf.Core.Dto;
using MapleLeaf.Model.CookBook.Menu.Entity;
using MapleLeaf.Model.CookBook.Organization.Relation;
using MapleLeaf.WebApi.CookBook.Controllers.Dto;
using MapleLeaf.WebApi.CookBook.Controllers.Paramters;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;
using SqlSugar;
using System.Threading.Tasks;

namespace MapleLeaf.WebApi.CookBook.Controllers.SystemManagement
{
    /// <summary>
    /// 用户管理
    /// </summary>
    public class MenusController : ApiBaseController
    {
        private readonly IRedisHelper _redisHelper;
        private readonly SystemClient _systemClient;
        private readonly OrganizationClient _organizationClient;
        /// <summary>
        /// 构造函数
        /// </summary>
        public MenusController(IRedisHelper handler, SystemClient systemClient, OrganizationClient organizationClient)
        {
            _redisHelper = handler;
            _systemClient = systemClient;
            _organizationClient = organizationClient;
        }

        /// <summary>
        /// 菜单路由列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<RouteVo>>> GetRoutes()
        {
            var routes = new List<RouteVo>();

            var whereExp = Expressionable.Create<MenuEntity>();
            whereExp = whereExp.And(it => it.Type == (int)MenuTypeEnum.Menu || it.Type == (int)MenuTypeEnum.Catalog);
            var list = await _systemClient.GetMenuListAsync(whereExp.ToExpression());
            routes = list.ToRouteVoList();

            return Success(routes);
        }
        /// <summary>
        /// 
        /// </summary>
        private async Task InitMenuAsync(List<MenuVo> routes, long parentId = 0)
        {
            int index = 1;
            foreach (var item in routes)
            {
                var entity = item.Adapt<MenuEntity>();
                entity.Id = 0;
                entity.ParentId = parentId;
                entity.Sort = index++;
                var id = await _systemClient.SaveMenuAsync(entity);
                if (item.Children != null && item.Children.Count > 0)
                {
                    await InitMenuAsync(item.Children, id);
                }
            }
            await Task.CompletedTask;
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<MenuVo>>> GetMenuList()
        {
            var whereExp = Expressionable.Create<MenuEntity>();

            var list = await _systemClient.GetMenuListAsync(whereExp.ToExpression());
            var voList = list.GetTree();
            return Success(voList);
        }
        /// <summary>
        /// 获取菜单选项  
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<MenuOptionVo>>> GetMenuOptions(bool onlyParent)
        {
            var whereExp = Expressionable.Create<MenuEntity>();
            //whereExp = whereExp.And(it => it.Type == (int)MenuTypeEnum.Menu || it.Type == (int)MenuTypeEnum.Catalog);
            var list = await _systemClient.GetMenuListAsync(whereExp.ToExpression());
            var voList = list.GetMenuOptionTree();
            return Success(voList);
        }
        /// <summary>
        /// 保存菜单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> SaveMenu(MenuVo menu)
        {
            var entity = menu.Adapt<MenuEntity>();
            _ = await _systemClient.SaveMenuAsync(entity);
            return Success();
        }
        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<MenuVo>> GetMenu(long menuId)
        {
            var entity = await _systemClient.GetMenuInfoAsync(menuId);
            var vo = entity.Adapt<MenuVo>();
            return Success(vo);
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult> DeleteMenu(long menuId)
        {
            var res = await _systemClient.DeleteMenuAsync([menuId]);
            return res ? Success() : Fail();
        }
        /// <summary>
        /// 获取有权限的菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ApiResult<List<string>>> GetMenuIdsByRoleId(long roleid)
        {
            var res = await _organizationClient.GetRoleMenuListAsync(roleid);
            var ids = res?.Select(it => it.MenuId.ToString()).ToList() ?? [];
            return Success(ids);
        }
        /// <summary>
        ///  保存角色菜单
        /// </summary>
        /// <param name="parameter"></param>
        [HttpPost]
        public async Task<ApiResult> SaveRoleMenuList(RoleMenuParameter parameter)
        {
            var datas = parameter.MenuIds.Select(x => new RoleMenuEntity() { RoleId = parameter.RoleId, MenuId = x }).ToList();
            var res = await _organizationClient.SaveRoleMenuAsync(datas);
            return res ? Success("保存成功") : Fail("保存失败");
        }
    }
}
